package com.alice.item.service;

import com.alice.item.mapper.ItemRepository;
import com.alice.item.pojo.Item;
import com.alice.item.pojo.ItemForm;
import com.alice.item.pojo.ItemVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by caoxuel on 2020/9/22 13:20
 */
@Service
public class ItemService {
//
    @Autowired
    private ItemRepository itemRepository;

    /**
     * 根据id查询商品
     * @param id
     * @return
     */
    public Item queryById(Integer id){
        return itemRepository.getOne(id);
    }

    /**
     * 不查询已经删除的商品
     * @return
     */
    public List<Item> queryItemList(){
        return itemRepository.findByStatusNot(3);
    }

    /**
     * 添加商品
     * @param item
     */
    public void addItem(Item item){
        itemRepository.save(item);
    }

    /**
     * 逻辑删除商品
     * @param id
     */
    public void deleteById(Integer id){
        Item item = queryById(id);
        item.setStatus(3);
        //商品状态，1：正常 ，2：下架，3：删除
        itemRepository.save(item);
    }

    /**
     * 修改商品信息
     * @param itemForm
     */
    public void updateItem(ItemForm itemForm){
        Item item = queryById(itemForm.getId());
        item.setUpdated(new Date());
        item.setTitle(itemForm.getTitle());
        item.setStatus(itemForm.getStatus());
        item.setCid(itemForm.getCid());
        item.setNum(itemForm.getNum());
        item.setPrice(itemForm.getPrice());
        item.setSellPoint(itemForm.getSellPoint());

        itemRepository.save(item);
    }


    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param item
     * @return
     */
    //try1
    public Page<Item> queryPagedItem(Integer page, Integer pageSize, ItemVo item) {
        Item item1 = new Item();
        if(item!=null){
            if(item.getCid()!=null){
                item1.setCid(item.getCid());
            }
            if(StringUtils.isEmpty(item.getTitle())){
                item1.setTitle(item.getTitle());
            }
        }
        //item1.setStatus(3);
        Example<Item> example = Example.of(item1);
        Pageable pageable = new PageRequest(page-1,pageSize);
        //itemRepository.
        Page<Item> all = itemRepository.findAll(example, pageable);
        all.getTotalElements();
        all.getContent();
        return all;
    }

    //try2
    public Page<Item> search(Integer page, Integer pageSize,ItemVo item) {
        return itemRepository.findAll(new Specification<Item>() {
            @Override
            public Predicate toPredicate(Root<Item> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

                Predicate stuNameLike = null;
                if(null != item && !StringUtils.isEmpty(item.getTitle())) {
                    // 这里也可以root.get("name").as(String.class)这种方式来强转泛型类型
                    stuNameLike = cb.like(root.<String> get("title"), item.getTitle());
                }

                Predicate clazzNameLike = null;
                if(null != item && null != item.getCid()) {
                    clazzNameLike = cb.equal(root.<Integer> get("cid").<String> get("title"), item.getCid());
                }
                query.where(cb.notEqual(root.<Integer> get("status"), 3));
                if(null != clazzNameLike)
                    query.where(clazzNameLike);
                if(null != stuNameLike)
                    query.where(stuNameLike);

                return null;
            }
        }, new PageRequest(page - 1, pageSize));
    }

    //try3
    public Page<Item> search2(Integer page, Integer pageSize,ItemVo item) {

        // Specification查询构造器
        Specification<Item> specification = new Specification<Item>() {

            private static final long serialVersionUID = 1L;

            @Override
            public Predicate toPredicate(Root<Item> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                // 添加搜索条件
                if(null != item && !StringUtils.isEmpty(item.getTitle()))  {
                    predicates.add(criteriaBuilder.like(root.get("title"), "%"+item.getTitle()+ "%")); // id是表字段对应实体表属性
                }
                if(null != item && null != item.getCid()) {
                    predicates.add(criteriaBuilder.equal(root.get("cid"), item.getCid()));
                }
                predicates.add(criteriaBuilder.notEqual(root.get("status"), 3));
                // 把搜索条件连接（AND）起来
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        return itemRepository.findAll(specification,new PageRequest(page - 1, pageSize));
    }

}
